package com.example.questionbase.interceptor;


import com.example.questionbase.util.Result;
import com.example.questionbase.util.UserJwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Component
@Slf4j
public class AuthorizeInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.登录放行
        if (request.getRequestURI().contains("login")) {
            return true;
        }

        //获取token
        String token = request.getHeader("token");

        //token为空
        if (StringUtils.isBlank(token)) {
            falseResult(response, "token为空!");
            return false;
        }

        //判断token是否有效
        try {
            Claims claimsBody = UserJwtUtil.getClaimsBody(token);
            int verifyToken = UserJwtUtil.verifyToken(claimsBody);

            if (verifyToken == 1 || verifyToken == 2) {
                falseResult(response, "token过期!");
                return false;
            }
        } catch (Exception e) {
            falseResult(response, "token过无效!");
            return false;
        }
        return true;
    }

    // Controller方法执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 整个请求完成后（包括Thymeleaf渲染完毕）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public void falseResult(HttpServletResponse response, String info) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Result result = Result.buildErrorResult(info);
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().println(objectMapper.writeValueAsString(result));
    }

}
